package com.ndp.fb.walle.business.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.ndp.fb.mongo.model.PromotedObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.ndp.fb.model.fbagent.param.adgroup.AdGroupParam;
import com.ndp.fb.model.fbagent.param.adset.AdSetParam;
import com.ndp.fb.mongo.api.AdGroupMongoService;
import com.ndp.fb.mongo.api.FaceBookJobMongoService;
import com.ndp.fb.mongo.model.AdForMongo;
import com.ndp.fb.mongo.model.AdSetForMongo;
import com.ndp.fb.mongo.model.FaceBookJob;
import com.ndp.fb.rdb.api.AdRdbService;
import com.ndp.fb.rdb.model.VpiInfo;
import com.ndp.fb.walle.business.AdGroupService;

/**
 * Created by hermen.he on 2015/4/22.
 */
@Component
public class AdGroupServiceImpl implements AdGroupService {

    private static Logger logger = LoggerFactory.getLogger(AdGroupServiceImpl.class);

    @Reference
    private AdRdbService adGroupRdbService;

    @Reference
    FaceBookJobMongoService faceBookJobMongoService;

    @Reference
    AdGroupMongoService adGroupMongoService;

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat format_job = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    /**
     * 根据adGroupId查询单价信息
     *
     * @param adGroupId 广告ID
     * @return 查询到的单价信息
     */
    @Override
    public VpiInfo findVpiFromCache(Long adGroupId) {
        return adGroupRdbService.findVpiFromCache(adGroupId);
    }

    /**
     * update_ad_creative: Ad updated
     * update_ad_friendly_name: Ad name updated
     * update_ad_run_status: Ad status updated
     */
    @Override
    public String createAdGroupJob(Long ad_id, String token, String newValue, String jobType) {
        AdForMongo adForMongo = adGroupMongoService.findAdForMongo(ad_id);
        FaceBookJob faceBookJob = new FaceBookJob();
        faceBookJob.setJob_id(UUID.randomUUID().toString());
        faceBookJob.setJob_batch(format_job.format(new Date()));
        faceBookJob.setJob_status("init");
        faceBookJob.setJob_sub_type(jobType);
        faceBookJob.setJob_time(format_job.format(new Date()));
        faceBookJob.setStart_time(new Date());
        faceBookJob.setJob_type("facebook_async");
        Map<String, Object> param = new HashMap<>();
        param.put("ad_id", ad_id);
        param.put("new_value", newValue);
        AdGroupParam adGroupParam = new AdGroupParam();
        adGroupParam.setFbAccountId(adForMongo.getAccount_id());
        adGroupParam.setAccessToken(token);
        adGroupParam.setAdGroupId(ad_id + "");
        if ("update_ad_run_status".equals(jobType)) {
            adGroupParam.setStatus(newValue);
            adGroupParam.setRedownload(true);
        }
        if ("update_ad_friendly_name".equals(jobType)) {
            adGroupParam.setName(newValue);
            adGroupParam.setRedownload(true);
        }
        
        if ("update_ad_creative".equals(jobType)) {
        	adGroupParam.setCreative_spec(newValue);
            adGroupParam.setRedownload(true);
        }
        param.put("adGroupParam", adGroupParam);
        faceBookJob.setParam(param);
        faceBookJobMongoService.saveFaceBookJob(faceBookJob);
        return faceBookJob.getJob_id();
    }

    @Override
    public FaceBookJob getAdGroupJob(String jobId) {
        return faceBookJobMongoService.getFaceBookJob(jobId);
    }

    @Override
    public String createAdSetJob(Long adSet_id, String token, String newValue, String jobType) {
        AdSetForMongo adSetForMongo = adGroupMongoService.findAdSetForMongo(adSet_id);
        FaceBookJob faceBookJob = new FaceBookJob();
        faceBookJob.setJob_id(UUID.randomUUID().toString());
        faceBookJob.setJob_batch(format_job.format(new Date()));
        faceBookJob.setJob_status("init");
        faceBookJob.setJob_sub_type(jobType);
        faceBookJob.setJob_time(format_job.format(new Date()));
        faceBookJob.setStart_time(new Date());
        faceBookJob.setJob_type("facebook_async");
        Map<String, Object> param = new HashMap<>();
        param.put("adSet_id", adSet_id);
        param.put("new_value", newValue);
        AdSetParam adSetParam = new AdSetParam();
        adSetParam.setFbAccountId(adSetForMongo.getAccount_id());
        adSetParam.setAccessToken(token);
        adSetParam.setAdSetId(adSet_id + "");
        if ("update_ad_set_run_status".equals(jobType)) {
            adSetParam.setStatus(newValue);
            adSetParam.setRedownload(true);
        } else if ("update_ad_set_name".equals(jobType)) {
            adSetParam.setName(newValue);
            adSetParam.setRedownload(true);
        } else if ("update_ad_set_bidding".equals(jobType)) {
            JSONObject object = JSONObject.parseObject(newValue);
            adSetParam.setBidAmount(object.getIntValue("bid_amount"));//单价
            adSetParam.setBillingEvent(object.getString("billing_event"));//收费方式
            adSetParam.setOptimizationGoal(object.getString("optimization_goal"));//优化方式

            adSetParam.setRedownload(true);
        } else if ("update_ad_set_budget".equals(jobType)) {
            JSONObject object = JSONObject.parseObject(newValue);
            adSetParam.setDailyBudget(object.getIntValue("daily_budget"));//每日预算  二选一  默认为0
            adSetParam.setLifetimeBudget(object.getIntValue("lifetime_budget"));//总预算
            adSetParam.setRedownload(true);
        } else if ("update_ad_set_targeting".equals(jobType)) {
        	adSetParam.setTargeting(newValue);
            adSetParam.setRedownload(true);
        } else if ("update_ad_set".equals(jobType)) {
            JSONObject object = JSONObject.parseObject(newValue);
            PromotedObject po = JSON.parseObject(adSetForMongo.getPromoted_object(), PromotedObject.class);
            po.setCustom_event_type(object.getString("custom_event_type"));
            adSetParam.setPromotedObject(po);
            if (object.containsKey("name")) {
                adSetParam.setName(object.getString("name"));
            }
            if (object.containsKey("status")) {
                adSetParam.setStatus(object.getString("status"));
            }
            if (object.containsKey("daily_budget")) {
                adSetParam.setDailyBudget(object.getIntValue("daily_budget"));
            }
            if (object.containsKey("lifetime_budget")) {
                adSetParam.setLifetimeBudget(object.getIntValue("lifetime_budget"));
            }
            if (object.containsKey("bid_amount")) {
                adSetParam.setBidAmount(object.getIntValue("bid_amount"));
            }
            if (object.containsKey("billing_event")) {
                adSetParam.setBillingEvent(object.getString("billing_event"));
            }
            if (object.containsKey("optimization_goal")) {
                adSetParam.setOptimizationGoal(object.getString("optimization_goal"));
            }
            if (object.containsKey("targeting")) {
                adSetParam.setTargeting(object.getString("targeting"));
            }
            if (object.containsKey("is_autobid")) {
                Boolean is_autobid = object.getBoolean("is_autobid");
                adSetParam.setAutobid(is_autobid);
                if (is_autobid) {
                    adSetParam.setBidAmount(null);
                }
            }
            if (object.containsKey("pacing_type")) {
                adSetParam.setPacingType(CollectionUtils.arrayToList(object.getJSONArray("pacing_type").toArray()));
            }
            adSetParam.setRedownload(true);
        }
        param.put("param", adSetParam);
        faceBookJob.setParam(param);
        faceBookJobMongoService.saveFaceBookJob(faceBookJob);

        return faceBookJob.getJob_id();
    }

    @Override
    public AdForMongo findAdForMongo(Long ad_id, String[] returnFields) {
        return adGroupMongoService.findAdForMongo(ad_id);
    }

    @Override
    public AdSetForMongo findAdSetForMongo(Long adSet_id, String[] returnFields) {
        return adGroupMongoService.findAdSetForMongo(adSet_id);
    }
}
